package com.compass.doctor.utils

import android.Manifest
import android.content.ClipData
import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.compass.doctor.R
import com.compass.framework.utils.getColorFromResource
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionDescriptionListener
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.widget.MediumBoldTextView
import com.yalantis.ucrop.UCrop

/**
 * Description： 图片选择工具
 * Date:2023/11/28 9:34
 */
private const val TAG_DESCRIPTION_VIEW = "TAG_DESCRIPTION_VIEW"
object SelectPicturesUtil {

    /**
     * 单选带相机 带压缩
     */
    fun selectPictures(context: Context, callbackListener: OnResultCallbackListener<LocalMedia>) {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())//只加载图片
            .setPermissionDescriptionListener(getPermissionDescriptionListener)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setSelectionMode(SelectModeConfig.MULTIPLE)//单选设置
            .isDirectReturnSingle(true)
            .isOriginalControl(true)//是否显示原图
            .forResult(callbackListener)

    }

    /**
     * 单选带相机 带压缩 带裁剪
     */
    fun selectPicturesCrop(
        context: Context,
        callbackListener: OnResultCallbackListener<LocalMedia>,
    ) {
        PictureSelector.create(context)

            .openGallery(SelectMimeType.ofImage())//只加载图片
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setPermissionDescriptionListener(getPermissionDescriptionListener)
            .setCropEngine(ImageFileCropEngine())//裁剪引擎
            .isOriginalControl(true)//是否显示原图
            .isDisplayCamera(true) //小米应用市场把相机先关闭
            .setSelectionMode(SelectModeConfig.SINGLE)//单选设置
            .isDirectReturnSingle(true)//不隐藏裁剪菜单
            .forResult(callbackListener)

    }

    /**
     * 单选带相机 带压缩 带裁剪
     */
    fun selectPicturesCropByListener(
        context: Context,
        callbackListener: OnResultCallbackListener<LocalMedia>,
    ) {
        PictureSelector.create(context)

            .openGallery(SelectMimeType.ofImage())//只加载图片
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setPermissionDescriptionListener(getPermissionDescriptionListener)
            .setCropEngine(ImageFileCropEngine())//裁剪引擎
            .isOriginalControl(true)//是否显示原图
            .setSelectionMode(SelectModeConfig.SINGLE)//单选设置
            .isDirectReturnSingle(true)//不隐藏裁剪菜单
            .forResult(callbackListener)

    }

    private val getPermissionDescriptionListener = object : OnPermissionDescriptionListener {
        override fun onPermissionDescription(
            fragment: Fragment,
            permissionArray: Array<String>
        ) {
            val viewGroup = fragment.requireView() as ViewGroup
            val dp10 = DensityUtil.dip2px(viewGroup.context, 10f)
            val dp15 = DensityUtil.dip2px(viewGroup.context, 15f)
            val view = MediumBoldTextView(viewGroup.context)
            view.tag = TAG_DESCRIPTION_VIEW
            view.textSize = 14f
            view.setTextColor(Color.parseColor("#333333"))
            view.setPadding(dp10, dp15, dp10, dp15)
            val title: String
            val explain: String
            when {
                TextUtils.equals(
                    permissionArray[0],
                    Manifest.permission.CAMERA
                ) -> {
                    title = "相机权限使用说明"
                    explain = "相机权限使用说明\n用户app用于拍照/录视频"
                }
                TextUtils.equals(
                    permissionArray[0],
                    Manifest.permission.RECORD_AUDIO
                ) -> {
                    title = "录音权限使用说明"
                    explain = "录音权限使用说明\n用户app用于采集声音"
                }
                else -> {
                    title = "存储权限使用说明"
                    explain = "存储权限使用说明\n用户app写入/下载/保存/读取/修改/删除图片、视频、文件等信息"
                }
            }
            val startIndex = 0
            val endOf = startIndex + title.length
            val builder = SpannableStringBuilder(explain)
            builder.setSpan(
                AbsoluteSizeSpan(
                    DensityUtil.dip2px(
                        viewGroup.context,
                        16f
                    )
                ), startIndex, endOf, Spannable.SPAN_INCLUSIVE_EXCLUSIVE
            )
            builder.setSpan(
                ForegroundColorSpan(-0xcccccd),
                startIndex,
                endOf,
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE
            )
            view.text = builder
            view.background = ContextCompat.getDrawable(
                viewGroup.context,
                R.drawable.ps_permission_desc_bg
            )
            val layoutParams = ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT
            )
//            layoutParams.topMargin = dpToPx(100)
            layoutParams.topToBottom = R.id.title_bar
            layoutParams.leftToLeft = ConstraintSet.PARENT_ID
            layoutParams.leftMargin = dp10
            layoutParams.rightMargin = dp10
            viewGroup.addView(view, layoutParams)
        }

        override fun onDismiss(fragment: Fragment) {
            val viewGroup = fragment.requireView() as ViewGroup
            viewGroup.removeView(viewGroup.findViewWithTag(TAG_DESCRIPTION_VIEW))
        }

    }


    /**
     * 多选带相机 带压缩
     */
    fun selectPicturesMultiple(
        context: Context,
        mData:List<LocalMedia>,
        callbackListener: OnResultCallbackListener<LocalMedia>
    ) {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())//只加载图片
            .setPermissionDescriptionListener(getPermissionDescriptionListener)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setSelectionMode(SelectModeConfig.MULTIPLE)//单选设置
            .isDirectReturnSingle(false)//
            .isOriginalControl(true)//是否显示原图
            .setSelectedData(mData)
            .forResult(callbackListener)

    }

    /**
     * 多选带相机 带压缩 带裁剪
     */
    fun selectPicturesMultipleCrop(
        context: Context,
        callbackListener: OnResultCallbackListener<LocalMedia>
    ) {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())//只加载图片
            .setPermissionDescriptionListener(getPermissionDescriptionListener)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .setCropEngine(ImageFileCropEngine())//裁剪引擎
            .setSelectionMode(SelectModeConfig.MULTIPLE)//单选设置
            .isDirectReturnSingle(false)//不隐藏裁剪菜单
            .isOriginalControl(true)//是否显示原图
            .forResult(callbackListener)

    }


    /**
     * 配置裁剪参数
     */
    fun buildOptions(): UCrop.Options {
        val options = UCrop.Options()
        options.setShowCropGrid(true)//是否显示裁剪框网格
        options.setShowCropFrame(true)//是否显示裁剪边框
        options.setFreeStyleCropEnabled(true)//裁剪框or图片拖动
        options.setHideBottomControls(false)//是否隐藏裁剪菜单栏
        options.setMaxScaleMultiplier(100f)
        options.setStatusBarColor(getColorFromResource(R.color.color_0165b8))
        options.setToolbarColor(getColorFromResource(R.color.color_0165b8))
        options.setToolbarWidgetColor(getColorFromResource(R.color.white))
        return options
    }


}